﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_record_logic.dart';
import 'exercise_record_state.dart';

/// 运动记录页面
/// 显示历史运动记录列表
class ExerciseRecordView extends GetView<ExerciseRecordLogic> {
  const ExerciseRecordView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(
          '运动记录',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: Obx(() {
          if (controller.state.isLoading.value) {
            return const Center(
              child: CircularProgressIndicator(
                color: Color(0xFFFFD700),
              ),
            );
          }

          return SingleChildScrollView(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 历史训练记录区域（合并后的唯一记录区域）
                _buildHistoryTrainingSection(),
              ],
            ),
          );
        }),
      ),
    );
  }

  /// 获取星期几名称
  String _getWeekdayName(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return '周${weekdays[weekday - 1]}';
  }

  /// 构建历史训练记录区域（合并后的唯一记录区域）
  Widget _buildHistoryTrainingSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Obx(() {
          // 按日期分组历史训练记录
          final groupedRecords = _groupHistoryRecordsByDate(
              controller.state.historyTrainingRecords);

          return Column(
            children: groupedRecords.entries.map((entry) {
              final date = entry.key;
              final records = entry.value;

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 日期标题
                  Text(
                    '${date.year}年${date.month.toString().padLeft(2, '0')}月${date.day.toString().padLeft(2, '0')}日, ${_getWeekdayName(date.weekday)}',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 8.h),

                  // 该日期的训练记录
                  ...records
                      .map((record) => GestureDetector(
                            onTap: () =>
                                controller.viewHistoryTrainingDetail(record),
                            child: Container(
                              margin: EdgeInsets.only(bottom: 16.h),
                              child: _buildHistoryTrainingRecordItem(record),
                            ),
                          ))
                      .toList(),

                  SizedBox(height: 16.h),
                ],
              );
            }).toList(),
          );
        }),
      ],
    );
  }

  /// 按日期分组历史训练记录
  Map<DateTime, List<HistoryTrainingRecord>> _groupHistoryRecordsByDate(
      List<HistoryTrainingRecord> records) {
    final grouped = <DateTime, List<HistoryTrainingRecord>>{};

    for (final record in records) {
      final date = DateTime(
          record.startTime.year, record.startTime.month, record.startTime.day);
      if (!grouped.containsKey(date)) {
        grouped[date] = [];
      }
      grouped[date]!.add(record);
    }

    // 按日期排序（最新的在前面）
    final sortedEntries = grouped.entries.toList()
      ..sort((a, b) => b.key.compareTo(a.key));

    return Map.fromEntries(sortedEntries);
  }

  /// 构建历史训练记录项
  Widget _buildHistoryTrainingRecordItem(HistoryTrainingRecord record) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        children: [
          // 左侧训练图标
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: const Color(0xFFFF6B35).withOpacity(0.2),
              borderRadius: BorderRadius.circular(24.r),
            ),
            child: Center(
              child: Text(
                _getTrainingTypeIcon(record.trainingType),
                style: TextStyle(
                  fontSize: 20.sp,
                ),
              ),
            ),
          ),

          SizedBox(width: 16.w),

          // 中间训练信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 训练类型和自动检测标签
                Row(
                  children: [
                    Text(
                      record.trainingName,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                    // 可以添加自动检测标签，这里暂时不显示
                  ],
                ),

                SizedBox(height: 8.h),

                // 训练详情
                Row(
                  children: [
                    // 时长
                    if (record.duration > 0) ...[
                      Row(
                        children: [
                          Icon(
                            Icons.access_time,
                            size: 12.sp,
                            color: const Color(0xFFFF6B35),
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '${(record.duration / 60).round()}分钟',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(width: 16.w),
                    ],

                    // 卡路里
                    if (record.calories > 0) ...[
                      Row(
                        children: [
                          Icon(
                            Icons.local_fire_department,
                            size: 12.sp,
                            color: const Color(0xFFFF6B35),
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '${record.calories}千卡',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(width: 16.w),
                    ],

                    // 心率（如果有）
                    if (record.averageHeartRate != null) ...[
                      Row(
                        children: [
                          Icon(
                            Icons.favorite,
                            size: 12.sp,
                            color: Colors.yellow,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '${record.averageHeartRate}BPM',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ],
            ),
          ),

          // 右侧时间和箭头
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '${record.startTime.hour.toString().padLeft(2, '0')}:${record.startTime.minute.toString().padLeft(2, '0')}',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[400],
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 8.h),
              Icon(
                Icons.arrow_forward_ios,
                size: 12.sp,
                color: Colors.grey[500],
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 获取训练类型图标
  String _getTrainingTypeIcon(int type) {
    switch (type) {
      case 0:
        return '🔥';
      case 1:
        return '🏃';
      case 2:
        return '🚶';
      case 3:
        return '🚴';
      case 4:
        return '🏊';
      case 5:
        return '💪';
      case 6:
        return '🧘';
      case 7:
        return '🏋️';
      case 8:
        return '💃';
      default:
        return '🏃‍♀️';
    }
  }

  /// 显示支持的训练类型
  void _showSupportedTrainingTypes() {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '支持的训练类型',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),
              Obx(() {
                if (controller.state.isQueryingSupportedTypes.value) {
                  return Container(
                    height: 200.h,
                    child: Center(
                      child: CircularProgressIndicator(
                        color: const Color(0xFFFFD700),
                      ),
                    ),
                  );
                }

                return Container(
                  height: 300.h,
                  child: ListView.builder(
                    itemCount: controller.state.supportedTrainingTypes.length,
                    itemBuilder: (context, index) {
                      final type =
                          controller.state.supportedTrainingTypes[index];
                      return Container(
                        margin: EdgeInsets.only(bottom: 8.h),
                        padding: EdgeInsets.all(12.w),
                        decoration: BoxDecoration(
                          color: type.isSupported
                              ? Colors.grey[900]
                              : Colors.grey[800],
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              type.isSupported
                                  ? Icons.check_circle
                                  : Icons.cancel,
                              color:
                                  type.isSupported ? Colors.green : Colors.red,
                              size: 20.sp,
                            ),
                            SizedBox(width: 12.w),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    type.name,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.white,
                                    ),
                                  ),
                                  Text(
                                    type.description,
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Colors.grey[400],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                );
              }),
              SizedBox(height: 16.h),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Get.back(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFFFD700),
                    foregroundColor: Colors.black,
                    padding: EdgeInsets.symmetric(vertical: 12.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  child: Text(
                    '关闭',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }

  /// 显示历史训练记录
  void _showHistoryTrainingRecords() {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '历史训练记录',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),
              Obx(() {
                if (controller.state.isQueryingHistory.value) {
                  return Container(
                    height: 300.h,
                    child: Center(
                      child: CircularProgressIndicator(
                        color: const Color(0xFFFFD700),
                      ),
                    ),
                  );
                }

                if (controller.state.historyTrainingRecords.isEmpty) {
                  return Container(
                    height: 200.h,
                    child: Center(
                      child: Text(
                        '暂无历史训练记录',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ),
                  );
                }

                return Container(
                  height: 400.h,
                  child: ListView.builder(
                    itemCount: controller.state.historyTrainingRecords.length,
                    itemBuilder: (context, index) {
                      final record =
                          controller.state.historyTrainingRecords[index];
                      return GestureDetector(
                        onTap: () {
                          Get.back();
                          controller.viewHistoryTrainingDetail(record);
                        },
                        child: Container(
                          margin: EdgeInsets.only(bottom: 8.h),
                          padding: EdgeInsets.all(12.w),
                          decoration: BoxDecoration(
                            color: Colors.grey[900],
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    record.trainingName,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.white,
                                    ),
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 8.w, vertical: 2.h),
                                    decoration: BoxDecoration(
                                      color:
                                          _getTrainingStateColor(record.state),
                                      borderRadius: BorderRadius.circular(4.r),
                                    ),
                                    child: Text(
                                      _getTrainingStateText(record.state),
                                      style: TextStyle(
                                        fontSize: 10.sp,
                                        color: Colors.white,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 8.h),
                              Row(
                                children: [
                                  Text(
                                    '${record.startTime.month}/${record.startTime.day} ${record.startTime.hour}:${record.startTime.minute.toString().padLeft(2, '0')}',
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Colors.grey[400],
                                    ),
                                  ),
                                  SizedBox(width: 16.w),
                                  Text(
                                    '${(record.duration / 60).round()}分钟',
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Colors.grey[400],
                                    ),
                                  ),
                                  SizedBox(width: 16.w),
                                  Text(
                                    '${record.calories}千卡',
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Colors.grey[400],
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                );
              }),
              SizedBox(height: 16.h),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Get.back(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFFFD700),
                    foregroundColor: Colors.black,
                    padding: EdgeInsets.symmetric(vertical: 12.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  child: Text(
                    '关闭',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }

  /// 获取训练状态颜色
  Color _getTrainingStateColor(TrainingState state) {
    switch (state) {
      case TrainingState.idle:
        return Colors.grey;
      case TrainingState.preparing:
        return Colors.orange;
      case TrainingState.running:
        return Colors.green;
      case TrainingState.paused:
        return Colors.yellow;
      case TrainingState.completed:
        return Colors.blue;
      case TrainingState.stopped:
        return Colors.red;
    }
  }

  /// 获取训练状态文本
  String _getTrainingStateText(TrainingState state) {
    switch (state) {
      case TrainingState.idle:
        return '空闲';
      case TrainingState.preparing:
        return '准备中';
      case TrainingState.running:
        return '训练中';
      case TrainingState.paused:
        return '已暂停';
      case TrainingState.completed:
        return '已完成';
      case TrainingState.stopped:
        return '已停止';
    }
  }
}
